package mamikeji.liaowa.ui.activity.right;

import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import jp.wasabeef.glide.transformations.BlurTransformation;
import mamikeji.liaowa.R;
import mamikeji.liaowa.application.MyApplication;
import mamikeji.liaowa.bean.ConstellationBean;
import mamikeji.liaowa.bean.DayRecommendedArticleBean;
import mamikeji.liaowa.bean.Wa_BabyMSG_Bean;
import mamikeji.liaowa.http_api.ForHttp;
import mamikeji.liaowa.http_api.HttpApi;
import mamikeji.liaowa.http_api.HttpKey;
import mamikeji.liaowa.ui.activity.BaseActivity;
import mamikeji.liaowa.ui.activity.article.ArticleTypeActivity;
import mamikeji.liaowa.ui.activity.article.Article_DetailsActivity;
import mamikeji.liaowa.ui.activity.circle.PreviewCircleImgActivity;
import mamikeji.liaowa.ui.activity.right.update.UpdateWaJieshaoActivity;
import mamikeji.liaowa.ui.adapter.Wa_Msg_ArticleAdapter;
import mamikeji.liaowa.utils.ForContents;
import mamikeji.liaowa.utils.ForLog;
import mamikeji.liaowa.utils.ForPreference;
import mamikeji.liaowa.utils.ForToast;
import mamikeji.liaowa.utils.MultiStateView;
import mamikeji.liaowa.widget.refreshView.PtrlDownRefreshFrameLayout;

public class BabyMSGActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "BabyMSGActicity";
    private static final int TAG_CIRCLE = 1001;
    private ListView listView_wa_msg_date;
    private PtrlDownRefreshFrameLayout ptrlDownRefreshFrameLayout_wa_msg_dat;
    private View header_view;

    private LinearLayout linearLayout_wa_msg_guanzhu , ll_baby_msg_top_bg;
    private RelativeLayout relativeLayout_baby_msg_top;
    public TextView textView_wamsg_momlogin_num,
            textView_wa_msg_guanzhubaby,
            textView_wa_msg_shengzhangnum,
            textView_wa_msg_edit,
            textView_wa_msg_time,
            textView_wamsg_article_more,
            textView_wa_msg_title,
            textView_wa_msg_jieshao,
            textView_wamsg_constellation_name,
            textView_wamsg_constellation_title,
            textView_wa_msg_weight,
            textView_wa_msg_heigh,
            textView_wamsg_constellation_content,
            textView_wa_msg_zan;
    private ImageView imageView_wa_msg_back , imageView_wa_msg_header_bg;
    private SimpleDraweeView imageView_wa_msg_titleimg,
            imageView_wamsg_constellation;

    private Wa_Msg_ArticleAdapter wa_msg_articleAdapter;
    private MultiStateView multiStateView_wa_msg_date;

    private List<DayRecommendedArticleBean.DataEntity> mList = new ArrayList<>();

    private String babyID;

    private Wa_BabyMSG_Bean wa_babyMSG_bean;

    private ConstellationBean constellationBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_baby_msg);
        getBase();
        tileBar(this, true);

        Intent mItent = getIntent();
        babyID = mItent.getStringExtra(ForContents.WA_DEFAULT_ID);

        init();
        initDate();
    }

    private void init() {
        ll_baby_msg_top_bg = (LinearLayout) findViewById(R.id.ll_baby_msg_top_bg);
        imageView_wa_msg_back = (ImageView) findViewById(R.id.imageView_wa_msg_back);
        textView_wa_msg_edit = (TextView) findViewById(R.id.textView_wa_msg_edit);
        textView_wa_msg_title = (TextView) findViewById(R.id.textView_wa_msg_title);
        ptrlDownRefreshFrameLayout_wa_msg_dat = (PtrlDownRefreshFrameLayout) findViewById(R.id.ptrlDownRefreshFrameLayout_wa_msg_dat);
        listView_wa_msg_date = (ListView) findViewById(R.id.listView_wa_msg_date);

        header_view = LayoutInflater.from(MyApplication.getContext()).inflate(R.layout.item_wa_msg_header, null);
        listView_wa_msg_date.addHeaderView(header_view);

        relativeLayout_baby_msg_top = (RelativeLayout) header_view.findViewById(R.id.relativeLayout_baby_msg_top);
        imageView_wa_msg_header_bg = (ImageView) header_view.findViewById(R.id.imageView_wa_msg_header_bg);
        linearLayout_wa_msg_guanzhu = (LinearLayout) header_view.findViewById(R.id.linearLayout_wa_msg_guanzhu);
        textView_wa_msg_weight = (TextView) header_view.findViewById(R.id.textView_wa_msg_weight);
        textView_wa_msg_heigh = (TextView) header_view.findViewById(R.id.textView_wa_msg_heigh);
        textView_wamsg_constellation_name = (TextView) header_view.findViewById(R.id.textView_wamsg_constellation_name);
        textView_wamsg_constellation_title = (TextView) header_view.findViewById(R.id.textView_wamsg_constellation_title);
        textView_wamsg_constellation_content = (TextView) header_view.findViewById(R.id.textView_wamsg_constellation_content);
        imageView_wamsg_constellation = (SimpleDraweeView) header_view.findViewById(R.id.imageView_wamsg_constellation);
        textView_wa_msg_zan = (TextView) header_view.findViewById(R.id.textView_wa_msg_zan);
        textView_wa_msg_shengzhangnum = (TextView) header_view.findViewById(R.id.textView_wa_msg_shengzhangnum);
        textView_wamsg_momlogin_num = (TextView) header_view.findViewById(R.id.textView_wamsg_momlogin_num);
        textView_wa_msg_guanzhubaby = (TextView) header_view.findViewById(R.id.textView_wa_msg_guanzhubaby);
        imageView_wa_msg_titleimg = (SimpleDraweeView) header_view.findViewById(R.id.imageView_wa_msg_titleimg);
        textView_wa_msg_time = (TextView) header_view.findViewById(R.id.textView_wa_msg_time);
        textView_wamsg_article_more = (TextView) header_view.findViewById(R.id.textView_wamsg_article_more);
        textView_wa_msg_jieshao = (TextView) header_view.findViewById(R.id.textView_wa_msg_jieshao);

        textView_wa_msg_jieshao.setOnClickListener(this);
        textView_wamsg_article_more.setOnClickListener(this);
        textView_wa_msg_edit.setOnClickListener(this);
        imageView_wa_msg_back.setOnClickListener(this);

        wa_msg_articleAdapter = new Wa_Msg_ArticleAdapter(mList, this);
        listView_wa_msg_date.setAdapter(wa_msg_articleAdapter);

        multiStateView_wa_msg_date = (MultiStateView) findViewById(R.id.multiStateView_wa_msg_date);

        multiStateView_wa_msg_date.getView(MultiStateView.VIEW_STATE_ERROR).findViewById(R.id.button_error_refish)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        multiStateView_wa_msg_date.setViewState(MultiStateView.VIEW_STATE_LOADING);
                        getBabyDate();
                    }
                });

        ptrlDownRefreshFrameLayout_wa_msg_dat.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, listView_wa_msg_date, header);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                textView_wamsg_momlogin_num.setText(ForPreference.getInt(ForContents.APP_COUNT) + "");
                textView_wa_msg_guanzhubaby.setText(ForPreference.getInt(ForContents.APP_WA_LIAO) + "");

                getBabyDate();
            }
        });

        listView_wa_msg_date.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (i != 0) {
                    Intent intent = new Intent(BabyMSGActivity.this, Article_DetailsActivity.class);
                    intent.putExtra("articleId", mList.get(i - 1).getArticleId() + "");
                    startActivity(intent);
                }
            }
        });

        listView_wa_msg_date.setOnScrollListener(new AbsListView.OnScrollListener() {
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                ll_baby_msg_top_bg.setBackgroundResource(R.color.color_app);
            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {
                int[] location = new int[2];
                relativeLayout_baby_msg_top.getLocationOnScreen(location);

                ForLog.i("location[1]",""+location[1]);

                if (location[1] <0){
                    ll_baby_msg_top_bg.setBackgroundResource(R.color.color_app);
                }else {
                    ll_baby_msg_top_bg.setBackgroundResource(R.color.color_00000000);
                }
            }


        });
    }


    private void initDate() {
        /*
         * 必须事先在assets底下创建一fonts文件夹 并放入要使用的字体文件(.ttf)
         * 并提供相对路径给creatFromAsset()来创建Typeface对象
         */
        Typeface fontFace = Typeface.createFromAsset(getAssets(),
                "fonts/main_text_css.ttf");
        // 字体文件必须是true type font的格式(ttf)；
        // 当使用外部字体却又发现字体没有变化的时候(以 Droid Sans代替)，通常是因为
        // 这个字体android没有支持,而非你的程序发生了错误
        textView_wa_msg_shengzhangnum.setTypeface(fontFace);
        textView_wamsg_momlogin_num.setTypeface(fontFace);
        textView_wa_msg_guanzhubaby.setTypeface(fontFace);
        textView_wa_msg_zan.setTypeface(fontFace);

        textView_wamsg_momlogin_num.setText(ForPreference.getInt(ForContents.APP_COUNT) + "");
        textView_wa_msg_guanzhubaby.setText(ForPreference.getInt(ForContents.APP_WA_LIAO) + "");

        getBabyDate();
    }

    public void getConstellation() {
        try {
            StringBuffer sb_constellation = new StringBuffer();
            InputStream is = getAssets().open("constellation.json");//打开json数据
            byte[] by = new byte[is.available()];//转字节
            int len = -1;
            while ((len = is.read(by)) != -1) {
                sb_constellation.append(new String(by, 0, len));//根据字节长度设置编码
            }
            is.close();//关闭流
            constellationBean = new Gson().fromJson(sb_constellation.toString(), ConstellationBean.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

        for (ConstellationBean.ConstellationListEntity entity : constellationBean.getConstellationList()) {
            if (entity.getName().equals(wa_babyMSG_bean.getUserBaby().getConstellation())) {
                textView_wamsg_constellation_name.setText(entity.getName());
                textView_wamsg_constellation_content.setText(entity.getContent());

                String titleString = getResources().getString(R.string.wa_msg_constellation_title);
                String titleFinal = String.format(titleString, entity.getName());
                textView_wamsg_constellation_title.setText(titleFinal);
                imageView_wamsg_constellation.setImageBitmap(getImageFromAssetsFile("constellation/" + entity.getImage()));
            }
        }
    }

    /**
     * 从Assets中读取图片  设置星座图片
     *
     * @param fileName
     * @return
     */
    private Bitmap getImageFromAssetsFile(String fileName) {
        Bitmap image = null;
        AssetManager am = getResources().getAssets();
        try {
            InputStream is = am.open(fileName);
            image = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return image;

    }

    public String mistiming(Long millisecond) {
        long timeStemp = 0;

        Date date = new Date(millisecond);
        timeStemp = date.getTime();

        long currentTimme = System.currentTimeMillis();
        ForLog.i("dd", timeStemp + "/" + currentTimme);
        long shijiaCha = currentTimme - timeStemp;
        ForLog.i("dd", shijiaCha + "/" + currentTimme);
        int count = 0;
        String timeString = "";
        //进行判断
        if (shijiaCha > 24 * 60 * 60 * 1000) {
            count = (int) (shijiaCha / (24 * 60 * 60 * 1000));
            if (count > 31) {
                int num = count / 31;
                int num_0 = count % 31;
                timeString = "我已经" + num + "个月" + (num_0 < 10 ? "零" + num_0 : num_0) + "天";
            } else {
                timeString = "我已经" + count + "天";
            }
        } else {
            timeString = "刚刚才开始";
        }

        timeString = "（" + timeString + "）";

        return timeString;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.textView_wa_msg_jieshao:
                Intent mIntent = new Intent(BabyMSGActivity.this, UpdateWaJieshaoActivity.class);
                mIntent.putExtra(ForContents.WA_describe, wa_babyMSG_bean.getUserBaby().getDescribe());
                mIntent.putExtra(ForContents.WA_ID, babyID);
                startActivityForResult(mIntent, TAG_CIRCLE);
                break;
            case R.id.imageView_wa_msg_back:
                finish();
                break;
            case R.id.textView_wa_msg_edit:
                if (wa_babyMSG_bean != null) {
                    if (wa_babyMSG_bean.getUserBaby() != null) {
                        if (wa_babyMSG_bean.getUserBaby().getId() > 0) {
                            Intent intent = new Intent(BabyMSGActivity.this, UpdateWaMSGActiity.class);
                            intent.putExtra("babyID", wa_babyMSG_bean.getUserBaby().getId() + "");
                            startActivityForResult(intent, RESULT_JUMP_CODE);
                        }
                    }
                }
                break;
            case R.id.textView_wamsg_article_more:
                startActivity(new Intent(BabyMSGActivity.this, ArticleTypeActivity.class));
                break;
            case R.id.imageView_wa_msg_titleimg:
                ArrayList<String> urlList = new ArrayList<>();
                urlList.add(wa_babyMSG_bean.getUserBaby().getAvatar());
                Intent intent = new Intent(BabyMSGActivity.this, PreviewCircleImgActivity.class);
                intent.putStringArrayListExtra("urlList", urlList);
                intent.putExtra("position", 1);
                intent.putExtra("img_url", true);
                startActivity(intent);
                break;
        }
    }

    private void getBabyDate() {
        Map<String, String> formMap = new HashMap<>();
        formMap.put(HttpKey.WA_DATE_ID, babyID);
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.USERBADY_DATE, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i(TAG, e.getMessage());
                ForToast.showToast(R.string.intent_error);
                multiStateView_wa_msg_date.setViewState(MultiStateView.VIEW_STATE_NOINTERNET);
                ptrlDownRefreshFrameLayout_wa_msg_dat.refreshComplete();
            }

            @Override
            public void onResponse(String response) {
                ForLog.i(TAG + "asdasdasdasdasd", response);
                ptrlDownRefreshFrameLayout_wa_msg_dat.refreshComplete();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        wa_babyMSG_bean = new Gson().fromJson(response, Wa_BabyMSG_Bean.class);
                        if (wa_babyMSG_bean.getUserBaby() != null) {
                            imageView_wa_msg_titleimg.setImageURI(Uri.parse(wa_babyMSG_bean.getUserBaby().getAvatar()));
                            ForPreference.putString(ForContents.WA_headerimg_url , wa_babyMSG_bean.getUserBaby().getAvatar());

                            //加载背景，
                            Glide.with(BabyMSGActivity.this)
                                    .load(wa_babyMSG_bean.getUserBaby().getAvatar())
                                    .dontAnimate()
                                    .error(R.drawable.img_baoziliaobeijing)
                                    // 设置高斯模糊
                                    .bitmapTransform(new BlurTransformation(BabyMSGActivity.this, 14, 2))
                                    .into(imageView_wa_msg_header_bg);

                            textView_wa_msg_time.setText(wa_babyMSG_bean.getUserBaby().getUserbobydescribe());
                            textView_wa_msg_title.setText(wa_babyMSG_bean.getUserBaby().getNickName());
                            if (wa_babyMSG_bean.getUserBaby().getDescribe() == null || wa_babyMSG_bean.getUserBaby().getDescribe().equals("")) {
                                textView_wa_msg_jieshao.setText(R.string.wa_msg_descrite_null);
                            } else {
                                textView_wa_msg_jieshao.setText(wa_babyMSG_bean.getUserBaby().getDescribe());
                            }
                            textView_wa_msg_shengzhangnum.setText(wa_babyMSG_bean.getUserBaby().getToDoCount() + "");
                            textView_wa_msg_zan.setText(wa_babyMSG_bean.getUserBaby().getThumbNum() + "");

                            linearLayout_wa_msg_guanzhu.setVisibility(wa_babyMSG_bean.getUserBaby().getStatus() == 2 ? View.GONE : View.VISIBLE);

                            getConstellation();

                            textView_wa_msg_heigh.setVisibility(wa_babyMSG_bean.getUserBaby().getStatus() == 2 ? View.VISIBLE : View.GONE);
                            textView_wa_msg_weight.setVisibility(wa_babyMSG_bean.getUserBaby().getStatus() == 2 ? View.VISIBLE : View.GONE);

                            String weightString = getResources().getString(R.string.wa_msg_yangyu_width);
                            String weightFinal = String.format(weightString, wa_babyMSG_bean.getUserBaby().getWeight());
                            String heighString = getResources().getString(R.string.wa_msg_yangyu_height);
                            String heighFinal = String.format(heighString, wa_babyMSG_bean.getUserBaby().getHeight());

                            textView_wa_msg_heigh.setText(heighFinal);
                            textView_wa_msg_weight.setText(weightFinal);

                            initdate();
                            multiStateView_wa_msg_date.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                        } else {
                            multiStateView_wa_msg_date.setViewState(MultiStateView.VIEW_STATE_EMPTY);
                        }
                    } else {
                        multiStateView_wa_msg_date.setViewState(MultiStateView.VIEW_STATE_ERROR);
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 获取每日推荐文章
     */
    private void initdate() {

        String url = HttpApi.ROOT_PATH + HttpApi.ARTICLE_day_recommended
                + "?usercode=" + ForPreference.getString(ForContents.USER_CODE);

        ForHttp.getMsg(url, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i(TAG, e.getMessage());
                ForToast.showToast(R.string.intent_error);
            }

            @Override
            public void onResponse(String response) {
                Log.e(TAG, response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        DayRecommendedArticleBean articleTypeBean = new Gson().fromJson(response, DayRecommendedArticleBean.class);
                        if (articleTypeBean.getData() != null) {
                            mList = articleTypeBean.getData();

                            wa_msg_articleAdapter.setList(mList);
                        }
                    } else {
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private static final int RESULT_JUMP_CODE = 103;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == RESULT_JUMP_CODE) {

            } else if (requestCode == TAG_CIRCLE) {
                getBabyDate();
            }
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        String weightString = getResources().getString(R.string.wa_msg_yangyu_width);
        String weightFinal = String.format(weightString, ForPreference.getString(ForContents.WA_weight));
        String heighString = getResources().getString(R.string.wa_msg_yangyu_height);
        String heighFinal = String.format(heighString, ForPreference.getString(ForContents.WA_heigh));

        textView_wa_msg_heigh.setText(heighFinal);
        textView_wa_msg_weight.setText(weightFinal);

        textView_wa_msg_title.setText(ForPreference.getString(ForContents.WA_nickname));

        imageView_wa_msg_titleimg.setImageURI(Uri.parse(ForPreference.getString(ForContents.WA_headerimg_url)));
    }
}
